package com.macauscholar.nfctest

import BaseNfcActivity
import android.content.Context
import android.content.Intent
import android.nfc.NdefMessage
import android.nfc.NdefRecord
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.Ndef
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.macauscholar.pickup.Test.TestKey
import kotlinx.android.synthetic.main.activity_write_text.*
import zhiyi.com.teacher_app.RsaKey
import java.nio.charset.StandardCharsets
import java.util.*

/**
 *  package : com.macauscholar.nfctest
 *  author : zhiyi
 *  date : 25/09/2020 11:56 AM
 *  project : NfcTest
 *  description :
 */
class WriteTextActivity :BaseNfcActivity(){
    var isWrite =false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_write_text)
        btn_write.setOnClickListener {
            isWrite=true
            btn_write.isEnabled=false
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        if (content_edit.text.toString()=="")return Toast.makeText(this,"输入不能为空",Toast.LENGTH_SHORT).show()
        //获取Tag对象
        if (isWrite){
            val detectedTag = intent.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG)
            val records: Array<NdefRecord?> = arrayOf(
                NdefRecord.createMime("application/octet-stream",
                    TestKey.encrypt(content_edit.text.toString().toByteArray(), RsaKey.publicKey))
            )
            val ndefMessage = NdefMessage(records)
            val result = writeTag(ndefMessage, detectedTag)
            if (result) {
                Toast.makeText(this, "写入成功", Toast.LENGTH_SHORT).show()
                btn_write.isEnabled=true
                content_edit.setText("")
            } else {
                Toast.makeText(this, "写入失败", Toast.LENGTH_SHORT).show()
                btn_write.isEnabled=true
                content_edit.setText("")
            }
        }
    }

    /**
     * 写数据
     *
     * @param ndefMessage 创建好的NDEF文本数据
     * @param tag         标签
     * @return
     */
    fun writeTag(ndefMessage: NdefMessage?, tag: Tag?): Boolean {
        try {
            val ndef = Ndef.get(tag)
            ndef.connect()
            ndef.writeNdefMessage(ndefMessage)
            return true
        } catch (e: Exception) {
            Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show()
        }
        return false
    }

}